package com.xssq.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xssq.domain.User;
import com.xssq.service.UserService;
import com.xssq.utils.response.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 *
 * @author xssq
 * @date 2023/08/13 08:41:05
 */
@RestController
@RequestMapping("/login")
@AllArgsConstructor
@Tag(name = "登录Controller")
public class LoginController {
    /**
     * 用户服务
     */
    private final UserService userService;

    /**
     * 登录
     *
     * @param loginUser 登录用户
     * @return {@link R}
     */
    @PostMapping("/getToken")
    @Operation(summary = "登录",description = "登录")
    public R login(@RequestBody User loginUser) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, loginUser.getUsername());
        wrapper.eq(User::getPassword, loginUser.getPassword());
        User one = userService.getOne(wrapper);
        if (ObjectUtil.isNotNull(one)) {
            StpUtil.login(one.getUsername());
//            StpUtil.getTokenSession().setLoginId(one.getUsername());
            return R.ok("登陆成功",StpUtil.getTokenValue());
        }
        return R.fail("登录失败,账号或密码错误");
    }

    /**
     * 退出
     *
     * @return {@link R}
     */
    @GetMapping("/exit")
    public R exit() {
        StpUtil.logout();
        return R.ok("退出登陆成功");
    }

    /**
     * 获取用户信息
     *
     * @return {@link R}
     */
    @GetMapping("/getUserInfo")
    public R getUserInfo() {
        Object loginId = StpUtil.getLoginId();
        System.err.println(loginId);
        return R.ok("获取用户信息成功",loginId);
    }
}
